package com.shuqi.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.ShuqiWebView;
import com.shuqi.activity.viewport.ShuqiWebView.IWebScroolListener;
import com.shuqi.common.Config;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.NetNotify;
import com.shuqi.common.Urls;
import com.shuqi.common.WebkitUrlDealer;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.dao.impl.TxtDownloadDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.TxtDownload;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.web.ShuqiWebJsBaseInterface;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.manager.TxtDownLoadManager;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * webkit网页浏览器 <br>
 * intent参数：String类型key值：WebKitActivity.ExtraKey_String_Url
 * 
 */
public class WebKitActivity extends ActivityBase implements OnClickListener {

    /** intent String 参数：打开的url */
    public static final String ExtraKey_String_Url = "TargetUrl";
    /** intent boolean 参数：是否检查用户状态（游客注册不需要检查身份） */
    public static final String ExtraKey_boolean_isCheckUser = "CheckUserState";
    public static final String ExtraKey_boolean_isHideBottom = "HideBottomState";

    private final String JsName = "anSQForWebJS";

    /** url功能key：保存神马网页书签 */
    private final String URLKEY_SAVEBOOKMARK = "application:saveBookMark:";
    /** url功能key：关闭webKit */
    private final String URLKEY_CLOSEWEBKIT = "appaction:close";

    @Deprecated
    /** url功能key：尝鲜版下载Apk */
    private final String URLKEY_DOWNLOADAPP = "application:updateapp:";

    private final String logTag = "WebKit";
    /** 网页主体 */
    private ShuqiWebView squareWeb;
    private View back;
    private TextView mTopUrlTitle;
    private View prePage;
    private View refresh;
    private View downLoad;
    private View webBottom;
    /** webview顶导航栏 */
    private View mTopView;
    /** 网页进度条 */
    private ProgressBar mProgressBar;

    /** 下载气泡提示view */
    private View webkit_bootom_download;

    private boolean isLoading;
    private WebkitUrlDealer urlDealer;

    /** 顶部兰显示的url：未经过处理 */
    private String srcUrl;
    private String firstUrl;
    private LinearLayout includeError;

    /** 展示对话框：是否重新下载:obj = BookName */
    private final int MSG_SHOWDIALOG_REDOWNLOAD = 1;
    /** 动作：下载Txt: obj = TxtDownload info */
    private final int MSG_DOWN = 2;
    /** 隐藏下载提示框 */
    private final int MSG_HIDEJUMP = 3;
    /** 隐藏重新下载提示框 */
    private final int MSG_HIDERELOAD = 4;
    /** 隐藏下载提示框 */
    private final int MSG_SHOWJUMP = 5;
    /** 隐藏重新下载提示框 */
    private final int MSG_SHOWRELOAD = 6;
    /** 更新顶部导航栏来源地址 */
    private final int MSG_SHOW_SOURCEADDRESS = 7;

    /** 开始下载提示：展示时间 短 */
    private final int TOAST_DELAYMILLIS_SHORT = 3000;
    /** 开始下载提示：展示时间 长 */
    private final int TOAST_DELAYMILLIS_LONG = 5000;

    /** 需要下载的离线正本书籍对象 */
    private TxtDownload info2 = null;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_SHOWDIALOG_REDOWNLOAD:
                    TxtDownload info1 = (TxtDownload) msg.obj;
                    Log4an.e(logTag, "已存在：" + info1.getBookName());
                    showReDownTips(info1);
                    break;
                case MSG_DOWN:
                    // TxtDownload info2 = (TxtDownload) msg.obj;
                    if (!Util.isNetworkConnected(WebKitActivity.this)) {
                        showMsg("请检查您的网络");
                        return;
                    }
                    info2 = (TxtDownload) msg.obj;
                    if (info2 != null) {
                        Log4an.e(logTag, "需要下载：" + info2.getBookName());
                        downLoadTxt(info2);
                    }
                    break;
                case MSG_SHOWJUMP:
                    showDownJumpTips(true);
                    break;
                case MSG_SHOWRELOAD:
                    showReDownTips(true);
                    break;
                case MSG_HIDEJUMP:
                    showDownJumpTips(false);
                    break;
                case MSG_HIDERELOAD:
                    showReDownTips(false);
                    break;
                case MSG_SHOW_SOURCEADDRESS:
                    if (!TextUtils.isEmpty(bookSourceUrl)) {
                        mTopUrlTitle.setText(bookSourceUrl);
                    }
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_webkit);
        if (Util.isWebViewProbablyCorrupt(this)) {
            ActivityManager.getInstance().finishActivity(this);
        }
        if (WebViewDatabase.getInstance(this) == null) {
            WebView oww = new WebView(this);
            oww.clearCache(true);
            ActivityManager.getInstance().finishActivity(this);
        }
        Log4an.i(logTag, "start init webkit");

        Intent intent = getIntent();
        // boolean isCheckUser = true;
        boolean isHideBottom = false;

        if (intent != null) {
            // isCheckUser = intent.getBooleanExtra(ExtraKey_boolean_isCheckUser, true);
            isHideBottom = intent.getBooleanExtra(ExtraKey_boolean_isHideBottom, false);
        }
        // 检查用户状态失败
        // if (isCheckUser && !isUserAvailable()) {
        // Log4an.i(logTag, "用户状态需要验证");
        // LoginActivity.openVerifyForResult(this, LoginActivity.LOGINTYPE_VERIFY);
        // ActivityManager.getInstance().finishActivity(this);
        // } else {
        // }
        urlDealer = new WebkitUrlDealer(this);
        initPage();
        activityInitData();

        if (isHideBottom && webBottom != null) {
            webBottom.getLayoutParams().height = 0;
        }
    }

    /***
     * 用户状态是否可使用webkit
     * 
     * @return
     */
    private boolean isUserAvailable() {
        UserInfo userInfo = MyAccountManager.getInstance(this, true);
        if ((MyAccountManager.isVipUser(userInfo) || MyAccountManager.isCommonUser(userInfo))
                && !MyAccountManager.isNeedCheckUserState(userInfo)) {
            Log4an.i(logTag, "用户状态:正常");
            return true;
        } else {
            Log4an.i(logTag, "用户状态:需要验证");
            return false;
        }
    }

    private void initPage() {
        findViews();
        bindListeners();
        Intent intent = getIntent();
        srcUrl = intent.getStringExtra(ExtraKey_String_Url);
        firstUrl = urlDealer.dealUrl(new StringBuilder(50).append(srcUrl));
    }

    /** 初始化各种控件 */
    private void findViews() {
        squareWeb = (ShuqiWebView) findViewById(R.id.webkit_webview);
        prePage = findViewById(R.id.webkit_bootom_pre);
        refresh = findViewById(R.id.webkit_bootom_refresh);
        downLoad = findViewById(R.id.webkit_bootom_download);
        mTopUrlTitle = (TextView) findViewById(R.id.webkit_top_title);
        back = findViewById(R.id.webkit_top_back);
        webBottom = findViewById(R.id.webkit_bootom);
        mTopView = (View) findViewById(R.id.web_title);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        webkit_bootom_download = (View) findViewById(R.id.bubble_hint);
        if (FunctionsSwitch.isShowDownloadHint(this)) {
            webkit_bootom_download.setVisibility(View.VISIBLE);// 显示下载气泡
        }
    }

    /** 各种控件绑定监听事件 */
    private void bindListeners() {
        back.setOnClickListener(this);
        prePage.setOnClickListener(this);
        refresh.setOnClickListener(this);
        downLoad.setOnClickListener(this);
    }

    /**
     * 保存神马网页书签：必须转码前截取各字段
     * 
     * @param url 格式： <BR>
     *        saveBookMark:书籍ID:书名:章节名:网页地址:章节Id:来源ID <BR>
     *        application:saveBookMark:93764:%E6%AD%A6%E9%80%86%E4%B9%BE%E5%9D%A4:%E7%AC%AC%E4%B8%80
     *        %E7%AB%A0 %E5%BA%9F%E7%89%A9%E5%8D%97:http%3A%2F%2Fsoutouch.3gpp.cn%2Fi.php%3Fct
     *        %3Dbook%26ac%3Din%26bid%3D93764%26chapterid%3D1%26sourceid%3D160:1:160
     */
    private void saveShenMaWebBookMark(String url) {
        Log4an.e(logTag, "保存神马网页书签=" + url);

        UserInfo userInfo = MyAccountManager.getInstance(getApplicationContext());

        if (!MyAccountManager.isGuestUser(userInfo) && !TextUtils.isEmpty(url)
                && url.startsWith(URLKEY_SAVEBOOKMARK)) {
            String markStr = url.replace(URLKEY_SAVEBOOKMARK, "");
            String markKey[] = markStr.split(":");
            try {
                if (markKey != null && markKey.length >= 7) {
                    for (int i = 0; i < markKey.length; i++) {
                        markKey[i] = URLDecoder.decode(markKey[i], "UTF-8");
                        Log4an.i(logTag, "书签数据：" + i + " " + markKey);
                    }
                    BookMarkInfo info = new BookMarkInfo();
                    info.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK);
                    info.setBookId(markKey[0]);
                    info.setBookName(markKey[1]);
                    info.setChapterName(markKey[2]);
                    info.setFilePath(markKey[3]);
                    info.setChapterId(markKey[4]);
                    info.setSourceId(markKey[5]);
                    info.setBookCoverImgUrl(markKey[6]);;
                    info.setPercent(markKey[7]);
                    info.setUserId(userInfo.getUserId());
                    BookMarkInfoDao.getInstance().saveBookMark(info);
                } else {
                    Log4an.e(logTag, "保存神马网页书签: save error keys < 7 ");
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log4an.e(logTag, "保存神马网页书签: save error");
            }
        } else {
            Log4an.e(logTag, "保存神马网页书签: error 格式");
        }
    }

    /**
     * 监听webview的一些事件，处理功能 开始，结束加载事件；进度事件；标题获取事件；
     */
    public void activityInitData() {

        includeError = (LinearLayout) findViewById(R.id.include_error);

        findViewById(R.id.retry).setVisibility(View.GONE);// 产品需求 该界面底部有刷新按钮，此处需去掉无网络报错的重试按钮

        squareWeb.getSettings().setJavaScriptEnabled(true);
        squareWeb.getSettings().setDomStorageEnabled(true);

        squareWeb.addJavascriptInterface(new JavaScriptInterface(), JsName);

        // 缩放功能
        squareWeb.getSettings().setSupportZoom(true);
        squareWeb.getSettings().setBuiltInZoomControls(true);

        squareWeb.setScroolListener(new IWebScroolListener() {

            @Override
            public boolean open() {
                if (!mIsShowTopView) {
                    return mChangeSearchBoxStates();
                } else {
                    return false;
                }
            }

            @Override
            public boolean close() {
                if (mIsShowTopView) {
                    return mChangeSearchBoxStates();
                } else {
                    return false;
                }
            }
        });



        squareWeb.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        squareWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log4an.d(logTag, "load url=" + url);
                if (TextUtils.isEmpty(url)) {
                    return true;
                }
                if (url.startsWith("http")) {
                    srcUrl = url;
                    view.loadUrl(urlDealer.dealUrl(new StringBuilder(50).append(url)));
                } else if (URLKEY_CLOSEWEBKIT.equals(url)) {// 关闭浏览器
                    ActivityManager.getInstance().finishActivity(WebKitActivity.this);
                } else if (url.startsWith(URLKEY_SAVEBOOKMARK)) {// 保存书签
                    saveShenMaWebBookMark(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log4an.d(logTag, "onPageStarted");
                onLoadPageStart();

                mProgressBar.setProgress(0);
                mProgressBar.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log4an.d(logTag, "onPageFinished");
                onLoadPageFinish();

                mProgressBar.setVisibility(View.GONE);

                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                    String failingUrl) {
                Log4an.d(logTag, "onReceivedError:" + errorCode + ", " + description);
                super.onReceivedError(view, errorCode, description, failingUrl);
                includeError.setVisibility(View.VISIBLE);
                squareWeb.setVisibility(View.GONE);
                onLoadPageFinish();
            }

        });
        squareWeb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mProgressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (TextUtils.isEmpty(bookSourceUrl)) {
                    WebKitActivity.this.mTopUrlTitle.setText(srcUrl);
                } else {
                    WebKitActivity.this.mTopUrlTitle.setText(bookSourceUrl);
                    bookSourceUrl = null;
                }
                super.onReceivedTitle(view, title);
            }

        });

        // 屏蔽复制
        squareWeb.setOnLongClickListener(new WebView.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        squareWeb.loadUrl(firstUrl);
    }


    /** 页面加载完成：更新图标，更新加载状态标识 */
    private void onLoadPageFinish() {
        if (squareWeb.canGoBack()) {
            prePage.setBackgroundResource(R.drawable.icon_webkit_bottom_pre_selector);
        } else {
            prePage.setBackgroundResource(R.drawable.icon_webkit_bottom_back_selector);
        }
        refresh.setBackgroundResource(R.drawable.icon_webkit_bottom_refresh_selector);
        isLoading = false;
    }

    /** 页面开始加载：更新图标，更新加载状态标识 */
    private void onLoadPageStart() {
        if (squareWeb.canGoBack()) {
            prePage.setBackgroundResource(R.drawable.icon_webkit_bottom_pre_selector);
        } else {
            prePage.setBackgroundResource(R.drawable.icon_webkit_bottom_back_selector);
        }
        refresh.setBackgroundResource(R.drawable.icon_webkit_top_back_selector);
        isLoading = true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_PHONEKEY_BACK);
                if (event.getRepeatCount() == 0) {
                    if (squareWeb != null && firstUrl.equals(squareWeb.getUrl())) {
                        // 如果是首页则正常退出
                        // ActivityManager.getInstance().finishActivity(this);
                        ActivityManager.getInstance().bottomFinishActivity(this);
                        return true;
                    } else if (squareWeb != null && squareWeb.canGoBack()) {
                        squareWeb.goBack();
                        bookSourceUrl = null;
                        return true;
                    }
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.webkit_top_back:// 关闭
                StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_TOP_BACK);
                // ActivityManager.getInstance().finishActivity(this);
                ActivityManager.getInstance().bottomFinishActivity(this);
                // showJumpTxtDownLoadToast();
                break;
            case R.id.webkit_bootom_pre:// 上一页
                if (squareWeb.canGoBack()) {
                    squareWeb.goBack();
                    bookSourceUrl = null;
                } else {
                    // ActivityManager.getInstance().finishActivity(this);
                    ActivityManager.getInstance().bottomFinishActivity(this);
                }
                StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_BOTTOM_BACK);
                break;
            case R.id.webkit_bootom_refresh:// 刷新
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
                    @Override
                    public void netErrorCallback() {
                        includeError.setVisibility(View.GONE);
                        squareWeb.setVisibility(View.VISIBLE);
                        if (isLoading) {// 停止功能
                            squareWeb.stopLoading();
                        } else {// 刷新功能
                            squareWeb.reload();
                        }
                    }
                });
                StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_BOTTOM_REFRESH);
                break;
            case R.id.webkit_bootom_download:// 下载
                if (FunctionsSwitch.isShowDownloadHint(this)) { // 如果当前有下载任务，并且正显示气泡
                    webkit_bootom_download.setVisibility(View.GONE);
                    findViewById(R.id.view_webkit_toast_jump).setVisibility(View.GONE);
                    FunctionsSwitch.setShowDownloadHint(this, false); // 点击后置为不显示
                }
                BookDownloadActivity.show(this);
                StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_BOTTOM_DOWNLOAD);
                break;
            case R.id.retry:
                if (!Util.isNetworkConnected(this)) {
                    return;
                }
                includeError.setVisibility(View.GONE);
                squareWeb.setVisibility(View.VISIBLE);
                if (isLoading) {// 停止功能
                    squareWeb.stopLoading();
                } else {// 刷新功能
                    squareWeb.reload();
                }
                break;
            case R.id.view_webkit_toast_jump_bt: // 点击查看
                BookDownloadActivity.show(WebKitActivity.this);
                if (FunctionsSwitch.isShowDownloadHint(this)) { // 如果当前有下载任务，并且正显示气泡
                    findViewById(R.id.view_webkit_toast_jump).setVisibility(View.GONE);
                    webkit_bootom_download.setVisibility(View.GONE);
                    FunctionsSwitch.setShowDownloadHint(this, false); // 点击后置为不显示
                }
                StatisticsUtils.onEvent(WebKitActivity.this, StatisticsEventID.WEBKIT_TOST_JUMP);
                break;
            case R.id.dialog_cancel_tv:
                hideNetWorkDialog();
                break;
            case R.id.dialog_confirm_tv:
                hideNetWorkDialog();
                NetNotify.getInstance().changeNotifyState(NetNotify.DOWNLOAD_BOOK_WEBKIT);
                // 点击2G或3G网络弹出框中的确定继续下载
                if (info2 != null) {
                    Log4an.e(logTag, "2G或3G网络下载：" + info2.getBookName());
                    downLoadTxt(info2);
                }
                break;
        }
    }


    /***
     * 下载文件：自动检查是否已存在
     * 
     * @param info
     */
    private void downLoadTxt(TxtDownload info) {
        if (info != null && !TextUtils.isEmpty(info.getDownloadUrl())) {
            boolean isShow = isShowNetWorkDialog();
            Log4an.e(logTag, "是否需要显示网络弹框：" + isShow);
            if (!isShow) {
                if (!Util.isCanUseSdCard()) {
                    ToastUtil.showToastFullyCustomizable(this, "SD卡不可用,请检查...");
                    return;
                }
                TxtDownLoadManager.getInstance().downLoadBook(info);
                handler.sendEmptyMessage(MSG_HIDERELOAD);
                handler.sendEmptyMessage(MSG_SHOWJUMP);
                mShowDownLoadHint();
                StatisticsUtils.onEvent(WebKitActivity.this,
                        StatisticsEventID.WEBKIT_WEBCLICK_DOWNTXT);
            } else {
                showNetWorkDialog();
            }
        } else {
            Log4an.e(logTag, "下载参数有误：" + info);
        }
    }


    /** 点击下载按钮后显示下载气泡 */
    private void mShowDownLoadHint() {
        if (!FunctionsSwitch.isShowDownloadHint(this)) { // 如果当前没显示 则显示下载气泡
            webkit_bootom_download.setVisibility(View.VISIBLE);
            FunctionsSwitch.setShowDownloadHint(this, true);
        }
    }

    /***
     * 提示该书已被下载提示框
     * 
     * @param bookName
     */
    private void showReDownTips(final TxtDownload info) {
        showReDownTips(true);
        findViewById(R.id.view_webkit_toast_redown_ok).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                message.what = MSG_DOWN;
                message.obj = info;
                handler.sendMessage(message);
            }
        });
        findViewById(R.id.view_webkit_toast_redown_cancle).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showReDownTips(false);
                    }
                });
    }

    /***
     * 显示/隐藏：跳转下载页的提示框
     * 
     * @param isShow
     */
    private void showDownJumpTips(boolean isShow) {
        if (isShow) {
            findViewById(R.id.view_webkit_toast_jump).setVisibility(View.VISIBLE);
            findViewById(R.id.view_webkit_toast_jump_bt).setOnClickListener(this);
            StatisticsUtils.onEvent(this, StatisticsEventID.WEBKIT_WEBCLICK_STARTDOWNTXT);
            handler.removeMessages(MSG_HIDEJUMP);
            handler.sendEmptyMessageDelayed(MSG_HIDEJUMP, TOAST_DELAYMILLIS_SHORT);
        } else {
            findViewById(R.id.view_webkit_toast_jump).setVisibility(View.GONE);
            findViewById(R.id.view_webkit_toast_jump_bt).setOnClickListener(null);
        }
    }

    /***
     * 显示/隐藏：提示重复下载提示框
     * 
     * @param isShow
     */
    private void showReDownTips(boolean isShow) {
        if (isShow) {
            findViewById(R.id.view_webkit_toast_redown).setVisibility(View.VISIBLE);
            handler.removeMessages(MSG_HIDERELOAD);
            handler.sendEmptyMessageDelayed(MSG_HIDERELOAD, TOAST_DELAYMILLIS_LONG);
        } else {
            findViewById(R.id.view_webkit_toast_redown).setVisibility(View.GONE);
        }
    }

    /** js交互响应值 来源地址 */
    private final int action_sourceurl = 1;

    /**
     * webkit javascript接口回调
     * 
     * @author yanghuawei
     */
    public class JavaScriptInterface extends ShuqiWebJsBaseInterface {

        public JavaScriptInterface() {}

        /**
         * 访问网页封面：保存网页书籍浏览历史
         * 
         * @param bookId
         * @param bookName
         * @param bookType
         * @param imgUrl
         */
        public void saveScanHistory(String bookId, String bookName, String bookType, String imgUrl,
                String sourceId) {
            BookInfo info = new BookInfo();
            info.setUserId(MyAccountManager.getInstance(WebKitActivity.this).getUserId());
            info.setBookId(bookId);
            info.setBookName(bookName);
            info.setBookType(bookType);
            info.setBookCoverImgUrl(imgUrl);
            info.setSourceId(sourceId);
            info.setBookUpdateTime(System.currentTimeMillis());
            info.setSourceType(BookInfo.SOURCE_TYPE_SHEENME);
            info.setBookPayState(1);
            info.setBookPayMode(0);
            info.setBookPrice(0);
            info.setBookHistoryState(BookInfo.IN_HISTORY);// 需要加入到浏览历史里
            BookInfoDao.getInstance().saveOrUpdateBookInfo(info);
            Log4an.i(logTag, "saveScanHistory() bookId:" + bookId + ",bookName:" + bookType
                    + ",imgUrl:" + imgUrl + ",sourceId:" + sourceId);
        }

        /**
         * 网页封面点击“离线整本”下载txt
         * 
         * @param txtUrl
         * @param bookId
         * @param bookName
         */
        public void downLoadTxtBook(String txtUrl, String bookId, String bookName, long txtSize) {
            if (!TextUtils.isEmpty(txtUrl) && !TextUtils.isEmpty(bookId)) {
                try {
                    txtUrl = URLDecoder.decode(txtUrl, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                TxtDownload info = new TxtDownload();
                info.setUserId(MyAccountManager.getInstance(WebKitActivity.this).getUserId());
                info.setDownloadUrl(txtUrl);
                info.setBookId(bookId);
                info.setFileTotalSize(txtSize);
                info.setBookName(bookName);
                // info.setFileName(bookName + "_" + System.currentTimeMillis() + ".txt");
                info.setFileName(bookName + ".txt");
                info.setFilePath(Config.BOOK_YISOU_PATH);

                TxtDownload download =
                        TxtDownloadDao.getInstance().getTxtDownload(info.getBookId(),
                                info.getDownloadUrl());
                Message message = new Message();
                message.obj = info;
                if (download != null) {// 提示是否需要重新下载
                    message.what = MSG_SHOWDIALOG_REDOWNLOAD;
                } else {
                    message.what = MSG_DOWN;
                }
                handler.sendMessage(message);
            }
            Log4an.i(logTag, "downLoadTxtBook() txtUrl:" + txtUrl + ",bookId:" + bookId
                    + ",bookName:" + bookName);
        }

        /**
         * 网页获取书旗的书签信息
         * 
         * @param bookId
         * @param sourceId
         * @return
         */
        public String getBookMark(String bookId, String sourceId) {
            Log4an.i(logTag, "getBookMark() bookId:" + bookId + ",sourceId:" + sourceId);
            UserInfo userInfo = MyAccountManager.getInstance(getApplicationContext(), true);
            if (!MyAccountManager.isGuestUser(userInfo)) {// &&
                                                          // MyAccountManager.isNeedCheckUserState(userInfo)
                BookMarkInfo mark =
                        BookMarkInfoDao.getInstance().getBookMark(sourceId, bookId,
                                userInfo.getUserId(), BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK);

                if (mark != null) {
                    JSONObject jObject = new JSONObject();
                    try {
                        jObject.put("bookId", mark.getBookId());// 书id
                        jObject.put("chapterId", mark.getChapterId()); // 章节id
                        jObject.put("start", mark.getBookReadByte());// 开始
                        jObject.put("end", "0");// 结束
                        jObject.put("percent", mark.getPercent());// 进度
                        jObject.put("chapterName", mark.getChapterName());// 章节名
                        jObject.put("src", mark.getSourceId());// 来源

                        Log4an.i(logTag, "getBookMark() ok return :" + jObject.toString());
                        return jObject.toString();
                    } catch (JSONException e) {
                        Log4an.i(logTag, "getBookMark() error: " + e.toString());
                    }
                } else {
                    Log4an.i(logTag, "getBookMark() no BookMark bookId=" + bookId + ",sourceId="
                            + sourceId + ",userId=" + userInfo.getUserId());
                }
            } else {
                Log4an.i(logTag, "getBookMark() error: account error");
            }
            return "";
        }

        /**
         * 网页打开书旗阅读页阅读
         * 
         * @param bookId
         * @param chapterId
         * @param start
         * @param end
         * @param sourceId
         */
        public void readBook(String bookId, String chapterId, String start, String end,
                String sourceId, String bookName) {// ,
            Log4an.i(logTag, "readBook() bookId:" + bookId + ",chapterId:" + chapterId + "\nstart:"
                    + start + ",end:" + end + ",sourceId:" + sourceId + ",bookName:" + bookName);
            BookMarkInfo markInfo = new BookMarkInfo();
            markInfo.setUserId(MyAccountManager.getInstance(WebKitActivity.this).getUserId());
            markInfo.setBookId(bookId);
            markInfo.setChapterId(chapterId);
            markInfo.setBookName(bookName);
            markInfo.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK);
            markInfo.setSourceId(sourceId);
            EnterBookContent.jumpToBookContentByBookMark(WebKitActivity.this, markInfo, -1);
            StatisticsUtils.onEvent(StatisticsEventID.WEBKIT_JUMPAPP_READ);
        }

        /**
         * 通用js调用
         * 
         * @param action 响应字段
         * @param obj 可根据action不同下发不同的字符串数据 可以是xml，json...
         * @return
         * */
        public String onJSAction(int action, String obj) {
            switch (action) {
                case action_sourceurl:
                    mRefreshSourceUrl(obj);
                    break;
                default:
                    break;
            }
            return "daweinihao"; // 返回值为随便定义的值 真正需要返回数据类型时再做需要返回的地方做处理
        }

        @Override
        public void refresh() {
            if (squareWeb != null) {
                squareWeb.reload();
            }
        }

        @Override
        public Activity getActivity() {
            return WebKitActivity.this;
        }

        @Override
        public void loadError(String jsonData) {
            includeError.setVisibility(View.VISIBLE);
            squareWeb.setVisibility(View.GONE);
            onLoadPageFinish();
        }

    }

    /** 书籍来源地址 */
    private String bookSourceUrl;

    /** 更新书籍来源地址方法 */
    private void mRefreshSourceUrl(String obj) {
        try {
            if (!TextUtils.isEmpty(obj)) {
                JSONObject jsobj = new JSONObject(obj);
                String url = jsobj.getString("sourceUrl");
                if (!TextUtils.isEmpty(url)) {
                    bookSourceUrl = url;
                }
                Message message = new Message();
                message.what = MSG_SHOW_SOURCEADDRESS;
                handler.sendMessage(message);
                Log4an.e(logTag, "展示来源地址:" + url);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void activityLogicForward() {

    }



    /***
     * 打开webkit页面
     * 
     * @param activity
     * @param url
     */
    public static void openWebkit(final Activity activity, final String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent = new Intent(activity, WebKitActivity.class);
            intent.putExtra(WebKitActivity.ExtraKey_boolean_isCheckUser, true);
            intent.putExtra(WebKitActivity.ExtraKey_boolean_isHideBottom, false);
            intent.putExtra(WebKitActivity.ExtraKey_String_Url, url);
            ActivityManager.getInstance().startBottomNextActivity(intent, activity);
        } else {
            ToastUtil.showMessage("链接为空");
        }
    }

    /***
     * 打开webkit页面
     * 
     * @param activity
     * @param url
     */
    public static void openRegisterProtocol(Activity activity) {
        Intent intent = new Intent(activity, WebKitActivity.class);
        intent.putExtra(WebKitActivity.ExtraKey_boolean_isCheckUser, false);
        intent.putExtra(WebKitActivity.ExtraKey_boolean_isHideBottom, true);
        intent.putExtra(WebKitActivity.ExtraKey_String_Url,
                Urls.getWebRegisterProtocolUrl(activity));
        ActivityManager.getInstance().startBottomNextActivity(intent, activity);
    }


    /** 网络选择弹出框 */
    private Dialog mNetworkDialog;

    /** 显示网络选择框 */
    private void showNetWorkDialog() {
        if (isFinishing()) {
            return;
        }
        if (mNetworkDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.view_dialog_network, null);
            view.findViewById(R.id.dialog_cancel_tv).setOnClickListener(this);
            view.findViewById(R.id.dialog_confirm_tv).setOnClickListener(this);
            mNetworkDialog = new Dialog(this, R.style.net_dialog);
            LayoutParams params =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mNetworkDialog.addContentView(view, params);
            mNetworkDialog.setCanceledOnTouchOutside(true);
        }
        mNetworkDialog.show();
    }

    /** 隐藏网络选择框 */
    private void hideNetWorkDialog() {
        if (mNetworkDialog != null && mNetworkDialog.isShowing()) {
            mNetworkDialog.dismiss();
        }
    }


    /** 是否显示网络选择框 */
    private boolean isShowNetWorkDialog() {
        boolean isNoWifi =
                NetNotify.getInstance().isNeedNotifyNoWifi(NetNotify.DOWNLOAD_BOOK_WEBKIT);
        return isNoWifi;
    }



    /** 是否正在显示或隐藏mTopView */
    private boolean mIsRunningAnim = false;

    /** mTopView是否显示 */
    private boolean mIsShowTopView = true;

    /**
     * 根据当前mTopView当前状态，动态的显示隐藏mTopView
     */
    private boolean mChangeSearchBoxStates() {
        if (mIsRunningAnim) {
            return false;
        }
        mIsRunningAnim = true;
        final int height = mTopView.getHeight();
        final RelativeLayout.LayoutParams params =
                (android.widget.RelativeLayout.LayoutParams) mTopView.getLayoutParams();

        new Thread() {
            @Override
            public void run() {
                final int count = 30;
                for (int i = 0; i <= count; i++) {
                    if (mIsShowTopView) {
                        params.topMargin = -1 * i * height / count;
                    } else {
                        params.topMargin = -1 * (count - i) * height / count;
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            mTopView.setLayoutParams(params);
                        }
                    });
                    try {
                        sleep(6);
                    } catch (Exception e) {
                    }
                }
                try {
                    sleep(300);
                } catch (Exception e) {
                }
                mIsShowTopView = !mIsShowTopView;
                mIsRunningAnim = false;
            }
        }.start();
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ShuqiWebJsBaseInterface.JUMPLOGIN_REQUESTCODE
                && resultCode == Activity.RESULT_OK) {
            if (squareWeb != null) {
                squareWeb.reload();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
